package my.suveng.alarm.de;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.lang.NonNull;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * restTemplate拦截器, 请求跟踪
 * @author suwenguang
 * @date 2020/11/4 10:54 下午
 * @since 1.0
 */
public class TrackRestTemplateInterceptor implements ClientHttpRequestInterceptor {

    private static final Logger log = LoggerFactory.getLogger(TrackRestTemplateInterceptor.class);


    @Override
    public @NonNull ClientHttpResponse intercept(@NonNull HttpRequest httpRequest,@NonNull byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
        trackRequest(httpRequest, bytes);
        ClientHttpResponse httpResponse = clientHttpRequestExecution.execute(httpRequest, bytes);
        trackResponse(httpResponse);
        return httpResponse;
    }

    private void trackResponse(ClientHttpResponse httpResponse) throws IOException {
        log.info("status : {}, headers : {}", httpResponse.getStatusCode(), httpResponse.getHeaders());
    }

    private void trackRequest(HttpRequest request, byte[] body) {
        log.info("uri : {}, method : {} , body : {}, , headers : {}", request.getURI(), request.getMethod(), new String(body, StandardCharsets.UTF_8), request.getHeaders());
    }
}
